import logging
import json

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from sqlalchemy import desc
from sqlalchemy.exc import IntegrityError

from fidoweb.lib.base import Session, BaseController, render
from fidoweb.model.map import *

log = logging.getLogger(__name__)

class MapController(BaseController) :
	def addSchoolMapLocComment(self) :
		from fidoweb.model.map import SchoolMapLocComment
		from fidoweb.controllers.login import LoginController
		if ((not 'content' in request.POST) or (not 'id' in request.POST)) : return 'fail'
		loc_id = request.POST['id']
		content = request.POST['content']
		if (len(content) == 0 or Session.query(SchoolMapLoc).filter_by(id = loc_id).count() == 0) : return 'fail'
		lc = LoginController()
		user = lc._getLoginUser()
		if (user == None) : return 'notLoggedIn'
		c = SchoolMapLocComment(user.id, loc_id, content)
		Session.add(c)
		Session.commit()
		return 'success'
	
	def getDiscountByStoreId(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (not 'id' in request.GET) :
			return json.dumps(ret)
		store_id = request.GET['id']
		stores = Session.query(Store).filter_by(id = store_id)
		if (stores.count() == 0) :
			return json.dumps(ret)
		store = stores.first()
		from fidoweb.lib.algorithm import datetimeToStr
		for d in store.discounts :
			ret.append([d.id, d.name, datetimeToStr(d.createTime), datetimeToStr(d.validTime), datetimeToStr(d.expireTime), d.smallPic, d.largePic])
		return json.dumps(ret)
		
	def getSchoolMaps(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		for m in Session.query(SchoolMap) :
			ret.append([m.id, m.width, m.height, m.name, m.school_id])
		return json.dumps(ret)
	
	def getSchoolMapPiecesByMapId(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (not 'id' in request.GET) : 
			return json.dumps(ret)
		map_id = request.GET['id']
		for m in Session.query(SchoolMapPiece).filter_by(schoolMap_id = map_id) :
			ret.append([m.pos_x, m.pos_y, m.width, m.height, m.filename])
		return json.dumps(ret)
	
	def getSchoolMapLocComments(self) : 
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if ((not 'id' in request.GET)) : return json.dumps(ret)
		if ((not 'start' in request.GET) or (not 'end' in request.GET)) : return json.dumps(ret)
		loc_id = request.GET['id']
		start = int(request.GET['start'])
		end = int(request.GET['end'])
		if (end - start > 20 or end - start < 0) : return json.dumps(ret)
		from fidoweb.model.map import SchoolMapLocComment
		comments = Session.query(SchoolMapLocComment).order_by(desc(SchoolMapLocComment.id)).filter_by(schoolMapLoc_id = loc_id).slice(start, end)
		from fidoweb.lib.algorithm import datetimeToStr
		for c in comments :
			ret.append([c.content, datetimeToStr(c.createTime), c.user.name])
		return json.dumps(ret)
		
	def getSchoolMapLocCommentCount(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if ((not 'id' in request.GET)) : return json.dumps(ret)
		loc_id = request.GET['id']
		ret = Session.query(SchoolMapLocComment).order_by(desc(SchoolMapLocComment.id)).filter_by(schoolMapLoc_id = loc_id).count()
		return json.dumps([ret])
	
	def getSchoolMapLocDetails(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (not 'id' in request.GET) :
			return json.dumps(ret)
		loc_id = request.GET['id']
		for s in Session.query(SchoolMapLoc).filter_by(id = loc_id) :
			likeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = s.id).filter_by(type = 'like').count()
			dislikeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = s.id).filter_by(type = 'dislike').count()
			commentCount = Session.query(SchoolMapLocComment).filter_by(schoolMapLoc_id = s.id).count()
			ret.append([s.name, s.address, likeCount, dislikeCount, commentCount])
		return json.dumps(ret)
	
	def getSchoolMapLocsByMapId(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (not 'id' in request.GET) :
			return json.dumps(ret)
		map_id = request.GET['id']
		maps = Session.query(SchoolMap).filter_by(id = map_id)
		if (maps.count() == 0) : 
			return json.dumps(ret)
		curMap = maps.first()
		for s in curMap.mapLocs : 
			link = Session.query(SchoolMap_SchoolMapLoc).filter_by(schoolMap_id = curMap.id).filter_by(schoolMapLoc_id = s.id).first()
			if (s.store != None) :
				ret.append([s.id, link.pos_x, link.pos_y, s.name, s.address, 1])
			else :
				ret.append([s.id, link.pos_x, link.pos_y, s.name, s.address, 0])
		return json.dumps(ret)
	
	def getSchoolMapLocPics(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (not 'id' in request.GET) :
			return json.dumps(ret)
		loc_id = request.GET['id']
		locs = Session.query(SchoolMapLoc).filter_by(id = loc_id)
		if (locs.count() == 0) :
			return json.dumps(ret)
		curLoc = locs.first()
		for p in curLoc.pics :
			ret.append([p.type, p.filename])
		return json.dumps(ret)
		
	def getSchoolMapLocUserLike(self) :
		if (not 'id' in request.POST) :
			return 'error'
		loc_id = request.POST['id']
		from fidoweb.controllers.login import LoginController
		lc = LoginController()
		user = lc._getLoginUser()
		if (user == None) : 
			return 'notLoggedIn'
		suAll = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc_id).filter_by(user_id = user.id)
		if (suAll.count() == 0) :
			return 'unknown'
		else :
			return suAll.first().type
	
	def setSchoolMapLocUserLike(self) :
		if (not ('id' in request.POST) or (not 'type' in request.POST)) :
			return 'error'
		loc_id = request.POST['id']
		_type = request.POST['type']
		if (_type != 'like' and _type != 'dislike') :
			return 'error'
		from fidoweb.controllers.login import LoginController
		lc = LoginController()
		user = lc._getLoginUser()
		if (user == None) : 
			return 'notLoggedIn'
		try :
			su = SchoolMapLoc_User(loc_id, user.id, _type)
			Session.add(su)
			Session.commit()
		except IntegrityError as e :
			return 'fail'
		return 'success'